

const doCryPto = require('../utils/crypto.js');
const { getUserInfo, createUser, deleteUser } = require('../services/user.js')
const { SuccessModel, ErrorModel } = require('../model/ResModel.js');
const {registerUserNameNotExistInfo, registerUserNameExistInfo, registerFailInfo, loginFailInfo, deleteUserFailInfo } = require('../model/errorInfo.js')

async function isExist(userName) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    // {errno:0,data:userInfo}
    return new SuccessModel(userInfo)
  } else {
    return new ErrorModel(registerUserNameNotExistInfo)
  }
}


async function register({ userName, password, gender }) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    return new ErrorModel(registerUserNameExistInfo)
  } 
  const registerResult = await createUser({ 
    userName, 
    password: doCryPto(password), 
    gender
  });

  if (registerResult) {
    return new SuccessModel()
  } else {
    return new ErrorModel(registerFailInfo)
  }
} 


async function login(ctx, userName, password) {
  const userInfo = await getUserInfo(userName,doCryPto(password))
  if (!userInfo) {
    return new ErrorModel(loginFailInfo)
  } 
  if (!ctx.session.userInfo) {
    ctx.session.userInfo = userInfo;
  }
  return new SuccessModel()
}

async function deleteCurUser(userName) {
  const result =  await deleteUser(userName);
  if (result) {
    return new SuccessModel()
  } else {
    return new ErrorModel(deleteUserFailInfo)
  }
}

module.exports = {
  isExist,
  register,
  login,
  deleteCurUser
}